<!-- 商品管理分总 -->
<template>
  <div class="simple" simple>
    <div class="filter">
      <div class="l">
        <label
          >关键词搜索：
          <a-input placeholder="搜索产品、产品经理、设计师" v-model="search.keywords" @pressEnter="initQuery" class="filter-input">
            <a-icon type="search" slot="suffix" style="cursor: pointer;" @click="initQuery" />
          </a-input>
        </label>
        <label class="ml20"
          >百度状态：
          <a-select @change="initQuery" v-model="search.baiDuStatus" class="filter-select" placeholder="请选择百度状态">
            <a-select-option :value="-1">全部</a-select-option>
            <a-select-option :value="1">在线-未售罄</a-select-option>
            <a-select-option :value="2">下线-已售罄</a-select-option>
            <a-select-option :value="3">下线-未售罄</a-select-option>
          </a-select>
        </label>

        <label class="ml20"
          >排序：
          <a-select @change="initQuery" v-model="search.sortWithSales" class="filter-select" placeholder="请选择排序">
            <a-select-option :value="1">销量从高到低</a-select-option>
            <a-select-option :value="2">销量从低到高</a-select-option>
            <a-select-option :value="3">售价从高到低</a-select-option>
            <a-select-option :value="4">售价从低到高</a-select-option>
          </a-select>
        </label>

        <label class="ml20">搜索时间： <a-range-picker @change="initQuery" v-model="search.selectDate"/></label>
      </div>

      <div class="r">
        <a-button @click="reset">重置</a-button>
      </div>
    </div>

    <a-alert v-if="this.search.locationId && messageInfo" type="warning" style="margin:10px;height:40px;" close-text="我知道了">
      <div
        style="
        font-size: 10px;
        color: #e6a23c;"
        type="warning"
        slot="description"
      >
        <p style="margin-top:-10px">
          {{ messageInfo }}
        </p>
      </div>
    </a-alert>
    <div class="main-body" ref="mainBody">
      <a-table class="only-table" :expandRowByClick="true" :columns="columns" :pagination="false" :loading="loading" :dataSource="data" rowKey="id" :scroll="{ x: 500, y: tableHeight }">
        <template slot="locationName" slot-scope="text, record">
          <div class="only-table-locationName">
            <div v-if="record.goingOffline == 1" class="stauts">即将下线</div>
            <div>{{ record.locationName }}</div>
          </div>
        </template>
        <template slot="name" slot-scope="text, record">
          <p>产品名称：{{ record.productName | handleData }}</p>
          <p>商家名称：{{ record.shopsName | handleData }}</p>
          <p>产品品类：{{ record.categoryName | handleData }}</p>
          <p>发码方式：{{ record.codeTypeStr | handleData }}</p>
        </template>
        <template slot="people" slot-scope="text, record">
          <p>
            {{ record.productManagerName | handleData }}：{{ record.pmPhone | handleData }}
            <a-tag v-if="record.pmStatus === 3">
              已离职
            </a-tag>
          </p>
          <p>
            {{ record.editorName | handleData }}：{{ record.editPhone | handleData }}
            <a-tag v-if="record.editStatus === 3">已离职</a-tag>
          </p>
          <p>
            {{ record.designerName | handleData }}：{{ record.designerPhone | handleData }}
            <a-tag v-if="record.designerStatus === 3">已离职</a-tag>
          </p>
        </template>
        <template slot="item" slot-scope="text, record">
          <a-popover
            @visibleChange="
              (visible) => {
                visibleChange(visible, record)
              }
            "
            placement="bottom"
          >
            <template v-if="record.itemId" slot="content">
              <div style="display:flex;">
                <div style="width:150px">
                  <p v-if="record.itemStock">库存：{{ productItem.totalStocks | handleData }}</p>
                  <!-- <p v-if="record.itemStock">渠道库存：{{ productItem.channelStock | handleData }}</p> -->
                  <p>单次/最大购买量：{{ productItem.maximumPurchase | handleData }}</p>
                  <p>线上实际销量：{{ productItem.onlineRealSales | handleData }}</p>
                  <p>线上留单量：{{ productItem.onlineReservation | handleData }}</p>

                  <p>线上退款量：{{ productItem.onlineRefundAmount | handleData }}</p>
                  <p>商家核销量：{{ productItem.nuclearSales | handleData }}</p>
                </div>
                <div style="width:150px">
                  <p v-if="record.itemStock">剩余库存：{{ productItem.totalStocks | handleData }}</p>
                  <p>发码数量：{{ productItem.numberOfCodes | handleData }}</p>
                  <p>线下实际导单量：{{ productItem.offlineRealSales | handleData }}</p>
                  <p>线下留单量：{{ productItem.offlineReservation | handleData }}</p>
                  <p>线下退款量：{{ productItem.offlineRefundAmount | handleData }}</p>
                  <p>商城销量：{{ productItem.mallSalesWithProduct | handleData }}</p>
                  <!-- <p>请款量：{{ productItem.completeAmount | handleData }}</p> -->
                </div>
                <div style="width:150px">
                  <p>售价：{{ productItem.sellPriceYuan | handleData }}</p>
                  <p>原价：{{ productItem.originalPriceYuan | handleData }}</p>
                  <p>商家结算价：{{ productItem.settlementPriceYuan | handleData }}</p>
                  <p>渠道结算价：{{ productItem.channelPriceYuan | handleData }}</p>
                  <p>报量：{{ productItem.forShopsSales }}</p>
                </div>
                <div v-if="record.itemMoney === 1" style="width:150px">
                  <p>大达人佣金：{{ productItem.talentOfBigYuan || '0' }}.{{ productItem.talentOfMiddleYuan || '00' }}</p>
                  <!-- <p>中达人佣金：{{ productItem.talentOfMiddleYuan | handleData }}</p> -->
                  <p>小达人佣金：{{ productItem.talentOfSmallYuan | handleData }}</p>
                </div>
                <div v-if="record.itemMoney === 0" style="width:150px">
                  <p>大达人佣金：{{ record.talentOfBigYuan || '0' }}.{{ record.talentOfMiddleYuan || '00' }}</p>
                  <p>小达人佣金：{{ record.talentOfSmallYuan }}</p>
                </div>
              </div>
            </template>
            <span slot="title">套餐</span>
            <div class="flexDiv">
              <div>
                <p>套餐名：{{ record.itemName | handleData }}</p>
                <p>套餐ID：{{ record.itemId | handleData }}</p>
                <p v-if="record.itemMoney === 1">佣金：{{ record.itemTalentOfBigYuan | handleData }}.{{ record.itemTalentOfMiddleYuan || '00' }}/{{ record.itemTalentOfSmallYuan | handleData }}</p>
                <p v-if="record.itemMoney === 0">佣金：{{ record.talentOfBigYuan | handleData }}.{{ record.talentOfMiddleYuan || '00' }}/{{ record.talentOfSmallYuan | handleData }}</p>
                <p>发码数量：{{ record.numberOfCodes | handleData }}</p>
                <p>限购数量：{{ record.maximumPurchase | handleData }}</p>
                <p>实际销量：{{ record.itemRealSales | handleData }}</p>
              </div>
              <div>
                <p>售价：{{ record.salePriceYuan | handleData }}</p>
                <p>原价：{{ record.originPriceYuan | handleData }}</p>
                <p>商家结算价：{{ record.itemSettlePriceYuan | handleData }}</p>
                <p>渠道结算价：{{ record.itemChannelPriceYuan | handleData }}</p>
                <p>
                  <a v-if="record.itemNums > 1" @click.stop="viewDetails(record)">查看另外{{ record.itemNums - 1 }}个套餐</a>
                </p>
              </div>
            </div>
          </a-popover>
        </template>
        <template slot="numberTitle">
          <a-popover placement="right">
            <template slot="content">
              <div style="width:700px">
                <div>
                  线上实际销量+线下实际销量，实际销量已减去退款销量（当前产品下的所有套餐实际总销量之和）
                </div>
                <div>
                  管理员权限可看：
                  <p>
                    商城显示销量（300）=【初始销量（100）+线上实际销量（200）-留单量（10）】*销量显示速度（2）
                  </p>
                  <p>
                    实际总销量（200）=线上实际销量（100）+线下实际销量（100）
                  </p>
                  <p>总留单量（20）=线上留单量（10）+线下留单量（10）</p>
                  <p>总退款量（20）=线上退款量（10）+线下退款量（10）</p>
                  <p>线上请款销量（80）=线上实际销量（90）-线上留单量（10）</p>
                  <p>线下请款销量（0）=线下实际导单量（10）-线下留单量（10)</p>
                </div>
              </div>
            </template>
            <span slot="title">实际总销量</span>
            <span
              >数量
              <span class="tips">
                <i style="cursor : pointer"> <a-icon type="question-circle"/></i></span
            ></span>
          </a-popover>
        </template>
        <template slot="number" slot-scope="text, record">
          <div class="flexDiv">
            <div>
              <p>百度核销量：{{ record.baiDuOrderCompleteCount | handleData }}</p>
              <p>百度退款量：{{ record.baiDuOrderRefundCount | handleData }}</p>
              <p>剩余库存：{{ record.surplusStocks | handleData }}</p>
              <p>达人分享数：{{ record.sharingCount | handleData }}</p>
              <p style="color:red">百度销量：{{ record.baiDuOrderCount }}</p>
            </div>
          </div>
        </template>
        <template slot="time" slot-scope="text, record">
          <p>上线时间：{{ dateFormat(record.releaseTime) | handleData }}</p>
          <p>确认时间：{{ dateFormat(record.confirmTime) | handleData }}</p>

          <p>生效时间：{{ dateFormat(record.effectiveTime) | handleData }}</p>
          <p>结束时间：{{ dateFormat(record.endTime) | handleData }}</p>
          <p>到期时间：{{ dateFormat(record.expiryTime) | handleData }}</p>
        </template>
        <template slot="state" slot-scope="text, record">
          <p>{{ record.invalidWord }}</p>
          <p>{{ record.releaseStatusStr }}</p>
          <p v-if="record.isLongSold == 1">
            周边游爆品
            {{ record.visible === 1 ? '显示' : '隐藏' }}
          </p>
          <p v-if="record.isLongSold == 0">
            周边游推荐
            {{ record.aroundVisible === 1 ? '显示' : '隐藏' }}
          </p>
        </template>

        <template slot="action" slot-scope="text, record">
          <div>
            <a-button type="link" @click.stop="viewDetails(record)">
              套餐/产品详情
            </a-button>
            <a-button v-if="record.baiDuVisible == 1" type="link" style="color:red" @click="handleSetBdOnLineStatus(0, record.id)">
              下线百度
            </a-button>
          </div>
        </template>
        <template slot="qualificationUrlList" slot-scope="text, record">
          <template v-if="record.qualificationUrlList && record.qualificationUrlList.length > 0">
            <div>
              <upload v-show="record.qualificationUrlList && record.qualificationUrlList.length > 0" :limit="record.qualificationUrlList.length" disabled :value="record.qualificationUrlList"></upload>
            </div>
          </template>
          <template v-else>
            无
          </template>
        </template>
      </a-table>

      <a-modal class="copy-modal" :footer="null" :visible="copyProductModal" @cancel="copyProductModal = false" title="复制产品">
        <a-tabs>
          <a-tab-pane key="first" tab="选择站点">
            <div style="display:flex;justify-content: space-around;">
              <a-button type="primary" @click="nextButtonClick()">下一步</a-button>
            </div>
          </a-tab-pane>
          <a-tab-pane key="second" tab="设置配置" label="设置配置">
            <a-form-model ref="copyProductModalForm" :model="copyProductModalForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="是否复制海报" prop="poster">
                    <a-radio-group button-style="solid" v-model="copyProductModalForm.poster">
                      <a-radio-button :value="0">不复制</a-radio-button>
                      <a-radio-button :value="1">复制</a-radio-button>
                    </a-radio-group>
                    <!-- <a-switch v-model="copyProductModalForm.poster" checked-children="复制" un-checked-children="不复制" /> -->
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-item label="是否显示收货地址">
                    <a-radio-group v-model="copyProductModalForm.bookingShowAddress" button-style="solid">
                      <a-radio-button :value="0">不显示</a-radio-button>
                      <a-radio-button :value="1">显示</a-radio-button>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="是否复制产品合同">
                    <a-radio-group button-style="solid" v-model="copyProductModalForm.copyContract">
                      <a-radio-button :value="0">不复制</a-radio-button>
                      <a-radio-button :value="1">复制</a-radio-button>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="是否复制预约库存型号">
                    <a-radio-group button-style="solid" v-model="copyProductModalForm.copyBookingItem">
                      <a-radio-button :value="0">不复制</a-radio-button>
                      <a-radio-button :value="1">复制</a-radio-button>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="库存">
                    <a-input-number v-model="copyProductModalForm.stockAmount" :min="0"></a-input-number>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="单次最大购买量">
                    <a-input-number v-model="copyProductModalForm.singleMax" :min="0"></a-input-number>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="单次最小购买量">
                    <a-input-number v-model="copyProductModalForm.singleMin" :min="0"></a-input-number>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="销量">
                    <a-input-number v-model="copyProductModalForm.saleAmount" :min="0"></a-input-number>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div style="display:flex;justify-content: space-around;">
              <a-button type="primary" @click="lastButtonClick()">上一步</a-button>
              <a-button type="primary" @click="copyProduct()">确认复制</a-button>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-modal>
      <a-modal
        :visible="nationalModal"
        :bodyStyle="{
          'max-height': '600px',
          overflow: 'auto',
          padding: '0 24px'
        }"
        title="选择显示和隐藏站点"
        @cancel="nationalModal = false"
        @ok="handleNationalCheck"
        :width="850"
        :maskClosable="false"
      >
        <a-spin id="centerSpin" :spinning="spinning">
          <a-row v-for="(item, index) in selectLocationIdList" :key="item.province" style="border-bottom:1px solid #eee;padding:10px 0" justify="space-around" align="middle" :gutter="20">
            <a-col :span="4">
              <a-checkbox :indeterminate="item.indeterminate" :checked="item.checkAll" @change="(e) => onCheckAllChange(e, index)">{{ item.province }}</a-checkbox>
            </a-col>
            <a-col :span="20">
              <a-checkbox-group style="width:100%" v-model="item.checkedList" @change="(value) => checkChange(value, index)">
                <a-row>
                  <a-col v-for="el in item.locations" :key="el.id" :span="6">
                    <a-checkbox :value="el.id">{{ el.city }}</a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-col>
          </a-row>
        </a-spin>
      </a-modal>
      <a-modal :footer="null" :getContainer="() => $refs.mainBody" :visible="viewDetailsModal" :width="1100" @cancel="viewDetailsModal = false">
        <template slot="title">
          <span style="font-size:22px;">{{ viewDetailsModalRecord.locationName }}</span>
          <a-tag style="margin-left:8px" v-if="viewDetailsModalRecord.hasSoldOut === 1" color="orange">
            售罄
          </a-tag>
          <a-tag style="margin-left:8px" v-else-if="viewDetailsModalRecord.hasSoldOut === 0" color="cyan">
            未售罄
          </a-tag>
        </template>
        <div class="detailModal">
          <div>
            <div class="top">
              <div>
                <z-flag>名称/品类</z-flag>
                <p style="margin-top:20px">产品名称：{{ viewDetailsModalRecord.productName | handleData }}</p>
                <p>商家名称：{{ viewDetailsModalRecord.shopsName | handleData }}</p>
                <p>产品品类：{{ viewDetailsModalRecord.categoryName | handleData }}</p>
              </div>
              <div>
                <z-flag>人员</z-flag>
                <p style="margin-top:20px">
                  产品经理：{{ viewDetailsModalRecord.productManagerName | handleData }}/{{ viewDetailsModalRecord.pmPhone | handleData }}/{{ pmCompanyName }}
                  <a-tag v-if="viewDetailsModalRecord.pmStatus === 3">
                    已离职
                  </a-tag>
                </p>
                <p>
                  文案编辑：{{ viewDetailsModalRecord.editorName | handleData }}/{{ viewDetailsModalRecord.editPhone | handleData }}
                  <a-tag v-if="viewDetailsModalRecord.editStatus === 3">
                    已离职
                  </a-tag>
                </p>
                <p>
                  设计人员：{{ viewDetailsModalRecord.designerName | handleData }}/{{ viewDetailsModalRecord.designerPhone | handleData }}
                  <a-tag v-if="viewDetailsModalRecord.designerStatus === 3">
                    已离职
                  </a-tag>
                </p>
              </div>
            </div>
            <div class="top">
              <div>
                <z-flag>状态</z-flag>
                <p style="margin-top:20px">
                  {{ viewDetailsModalRecord.releaseStatusStr }}
                </p>

                <p>联联·本地商城{{ viewDetailsModalRecord.visible === 1 ? '显示' : '隐藏' }}</p>
                <p>联联·周边商城{{ viewDetailsModalRecord.aroundVisible === 1 ? '显示' : '隐藏' }}</p>
                <p>UU地方特产{{ viewDetailsModalRecord.regionVisible === 1 ? '显示' : '隐藏' }}</p>
              </div>
              <div>
                <z-flag>时间</z-flag>
                <p style="margin-top:20px">上线时间：{{ dateFormat(viewDetailsModalRecord.releaseTime) | handleData }}</p>

                <p>确认时间：{{ dateFormat(viewDetailsModalRecord.confirmTime) | handleData }}</p>

                <p>生效时间：{{ dateFormat(viewDetailsModalRecord.effectiveTime) | handleData }}</p>
                <p>结束时间：{{ dateFormat(viewDetailsModalRecord.endTime) | handleData }}</p>
                <p>到期时间：{{ dateFormat(viewDetailsModalRecord.expiryTime) | handleData }}</p>
              </div>
            </div>
            <div>
              <z-flag>数量</z-flag>
            </div>
            <div style="margin-top:20px" class="top">
              <div>
                <p>初始销量:{{ viewDetailsModalRecord.baseAmount | handleData }}</p>
                <p>商城销量:{{ viewDetailsModalRecord.sales | handleData }}</p>
                <!-- <p>渠道库存:{{ viewDetailsModalRecord.channelStock | handleData }}</p> -->
                <p>总核销量：{{ viewDetailsModalRecord.completeAmount | handleData }}</p>
                <p>总退款量：{{ viewDetailsModalRecord.refundAmount | handleData }}</p>
              </div>
              <div>
                <p>商家报量：{{ viewDetailsModalRecord.businessReportNums | handleData }}</p>
                <p>实际总销量：{{ viewDetailsModalRecord.realSales | handleData }}</p>
                <!-- <p>渠道销量:{{ viewDetailsModalRecord.channelSaleAmount | handleData }}</p> -->
                <p>总库存：{{ viewDetailsModalRecord.totalStocks | handleData }}</p>
                <p>剩余库存：{{ viewDetailsModalRecord.surplusStocks | handleData }}</p>

                <!-- <p>请款量：{{ record.requestAmount | handleData }}</p> -->
              </div>
            </div>
            <div>
              <div>
                <z-flag>地址</z-flag>
                <p style="margin-top:20px">
                  推广地址：<a :href="viewDetailsUrl">{{ viewDetailsUrl | handleData }}</a>
                </p>
                <p>
                  推文地址：<a :href="viewPushUrl">{{ viewPushUrl | handleData }}</a>
                </p>
              </div>
            </div>
          </div>

          <div>
            <div class="qrcode" ref="qrCodeUrl"></div>
            <p style="font-size: 12px;">请使用微信扫描二维码预览</p>
          </div>
        </div>
        <a-table rowKey="id" :loading="initLoading" :columns="innerColumns" :dataSource="productItemDetailList" :pagination="false">
          <template slot="number" slot-scope="text, row">
            <div class="flexDiv">
              <div>
                <p>剩余库存：{{ row.offlineRefundAmount | handleData }}</p>
                <p>百度销量：{{ row.baiDuOrderCount | handleData }}</p>
                <p>百度核销量：{{ row.baiDuOrderCompleteCount | handleData }}</p>
                <p>百度退款量：{{ row.baiDuOrderRefundCount | handleData }}</p>
              </div>
            </div>
          </template>
          <template slot="price" slot-scope="text, row">
            <p>售价：{{ row.sellPriceYuan | handleData }}</p>
            <p>原价：{{ row.originalPriceYuan | handleData }}</p>
            <p>商家结算价：{{ row.settlementPriceYuan | handleData }}</p>
            <p>渠道结算价：{{ row.channelPriceYuan | handleData }}</p>
          </template>
          <template slot="talentOfSmallYuan" slot-scope="text, row">
            <span v-if="viewDetailsModalRecord.itemMoney === 0">
              <p>大达人佣金：{{ viewDetailsModalRecord.talentOfBigYuan || '0' }}.{{ viewDetailsModalRecord.talentOfMiddleYuan || '00' }}</p>
              <p>小达人佣金：{{ viewDetailsModalRecord.talentOfSmallYuan | handleData }}</p>
            </span>
            <span v-else>
              <p>大达人佣金：{{ row.talentOfBigYuan || '0' }}.{{ row.talentOfMiddleYuan || '00' }}</p>
              <p>小达人佣金：{{ row.talentOfSmallYuan | handleData }}</p>
            </span>
          </template>
          <template slot="channelPrice" slot-scope="text, row">
            <span v-if="viewDetailsModalRecord.itemMoney === 0">{{ (row.sellPriceYuan - viewDetailsModalRecord.talentOfMiddleYuan - viewDetailsModalRecord.talentOfSmallYuan).toFixed(2) }}</span>
            <span v-else>{{ (row.sellPriceYuan - row.talentOfMiddleYuan - row.talentOfSmallYuan).toFixed(2) }} </span>
          </template>
        </a-table>
      </a-modal>
    </div>
    <div class="paging-container">
      <a-pagination
        size="small"
        :current="pagination.pageIndex"
        @change="onPaginationChange"
        showQuickJumper
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px 0;"
        :total="pagination.total"
        :pageSize="pagination.pageSize"
        showLessItems
      />
    </div>
  </div>
</template>

<script>
import { simple } from './mock'
import ZFlag from '@/components/ZFlag'
import { dateFormat } from 'nearby-common'
import upload from '@/components/upload/upload'
import { getShareUrl, authorityAdmin, getProductType, releaseUpdate, releaseManagerUpdate, checkNotice, companyWithUser, productItemByOne, getLocationAllProvince, getCommonApiSearch } from '@/service'
import { pointGetListOnInfo, getListOnInfoItem, setBdOnLineStatus as setBdOnLineStatusApi } from '@/service/baidu'

import moment from 'moment'
import debounce from 'lodash/debounce'
import QRCode from 'qrcodejs2'
import { mscf } from '@/util'
export default {
  name: 'pointIndex',
  components: { ZFlag, upload },
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    return {
      data: [],
      dateFormat,
      moment,
      // 抽屉
      showDrawer: false,
      columns: simple.columns,
      // 表格中的表格
      innerColumns: simple.innerColumns,
      // 展开的行
      expandedRowKeys: [],
      // 套餐数据
      productItemDetailList: [],
      // 子列表id
      productId: null,
      loading: false,
      initLoading: false,
      // 全部站点
      allStation: [],
      // 全部商城
      allProductType: [],
      // 搜索参数
      search: {
        keywords: '',
        // type: 1,
        locationId: -1,
        // 排序
        sortWithSales: undefined,
        // 搜索时间
        selectDate: [],
        // 百度状态 1-在线未售罄， 2-下线已售罄，3-下线未售罄，null是不参加条件
        baiDuStatus: -1,
        // 周边游状态 1-上线， 2-下线，null是不参加条件
        visible: null
      },
      // 分页
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // 弹出的套餐
      productItem: {},
      // 复制产品modal
      copyProductModal: false,
      // 复制产品的form
      copyProductModalForm: {
        poster: 0,
        bookingShowAddress: 0,
        copyContract: 0,
        copyBookingItem: 0,
        stockAmount: 0,
        singleMax: 0,
        singleMin: 0,
        saleAmount: 0,
        region: undefined,
        date1: undefined,
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      // 查看详情的Modal
      viewDetailsModal: false,
      viewDetailsUrl: '',
      viewPushUrl: '',
      viewDetailsModalRecord: {},
      // 查PM所属公司
      pmCompanyName: undefined,
      // 详情二维码url
      detailUrl: '',
      rules: {
        name: [
          {
            required: true,
            message: 'Please input Activity name',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 5,
            message: 'Length should be 3 to 5',
            trigger: 'blur'
          }
        ],
        date1: [{ required: true, message: 'Please pick a date', trigger: 'change' }],
        type: [
          {
            type: 'array',
            required: true,
            message: 'Please select at least one activity type',
            trigger: 'change'
          }
        ],
        resource: [
          {
            required: true,
            message: 'Please select activity resource',
            trigger: 'change'
          }
        ],
        desc: [
          {
            required: true,
            message: 'Please input activity form',
            trigger: 'blur'
          }
        ]
      },
      // 站点消息
      messageInfo: undefined,
      // 选择站点
      nationalModal: false,
      // 站点
      allReallyStation: [],
      // 选择的站点
      checkedList: [],
      selectLocationIdList: [],
      spinning: false,
      uploadKey: undefined
    }
  },
  async mounted() {
    this.setSearch()
    // 获取所有站点
    getCommonApiSearch()
      .then((res = []) => {
        this.allStation = res
      })
      // 获取失败依然继续请求列表数据
      .catch((err) => err)

    this.query()
    // 获取商城
    this.getAllProductType()
  },
  methods: {
    /**
     * 切换百度上下线状态
     * @param {number} baiDuVisible 1上线，0不上线
     * @param {number} bizProductId 产品id
     * @returns {void}
     */
    handleSetBdOnLineStatus(baiDuVisible, bizProductId) {
      const { $messageSend, $confirm, query } = this

      $confirm({
        title: baiDuVisible ? '上线百度' : '下线百度',
        content: baiDuVisible ? '确定要上线吗？' : '操作下线百度后，产品将从百度小程序下线，即在百度C端不显示，是否确认下线',
        onOk: () => {
          // 发送请求
          return setBdOnLineStatusApi({ baiDuVisible, bizProductId })
            .then((rs) => {
              query()
              $messageSend.success('操作成功')
            })
            .catch((err) => err)
        }
      })
    },

    getNotice() {
      checkNotice({ locationId: this.search.locationId }).then((res) => {
        this.messageInfo = res.info
      })
    },
    getAllStation(e) {
      getCommonApiSearch({ keywords: e }).then((res) => {
        console.log(res)
        this.allStation = res
      })
    },
    getAllProductType() {
      getProductType().then((res) => {
        this.allProductType = res
      })
    },

    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, locationId, keywords, beginTime, endTime, productType, sortWithSales } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          locationId: locationId ? Number(locationId) : undefined,
          sortWithSales: sortWithSales ? Number(sortWithSales) : undefined,
          selectDate: beginTime && endTime ? [moment(Number(beginTime)), moment(Number(endTime))] : [],
          //  selectDate: beginTime ? Number(beginTime) : null,
          //  endTime: endTime ? Number(endTime) : null,
          keywords
        }
      }
    },
    // 选择了站点
    changeLocation() {
      this.initQuery()
      this.getNotice()
    },
    // 分页查询
    onPaginationChange(page) {
      this.pagination.pageIndex = page
      this.query()
      this.setPath(this.getParams())
    },
    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { locationId, keywords, selectDate, sortWithSales, baiDuStatus, visible } = this.search

      return {
        pageIndex,
        pageSize,
        locationId: locationId == -1 ? null : locationId,
        sortWithSales,
        visible,
        keywords,
        baiDuStatus: baiDuStatus == -1 ? null : baiDuStatus,
        // type,
        // showStep,
        beginTime: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endTime: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },

    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    // 获取列表数据
    query() {
      this.loading = true
      pointGetListOnInfo(this.getParams())
        .then((res) => {
          this.data = res.data
          this.pagination.total = res.rowCount
        })
        .finally((e) => {
          this.loading = false
        })
    },
    // 打开复制产品modal
    showCopyProductModal(row) {
      this.copyProductModal = true
    },
    // 重置
    reset() {
      this.search = {
        keywords: '',
        // type: 1,
        locationId: undefined,
        sortWithSales: undefined,
        // showStep: 1,
        baiDuStatus: undefined,
        visible: undefined,
        // 搜索时间
        selectDate: []
      }
      const { path } = this.$route
      this.$router
        .replace({
          path,
          query: {}
        })
        .catch(() => {})
      this.initQuery()
    },
    // 新增产品
    launchProduct(row) {
      this.$router.push({ path: `/addOrEditCopyWriter/${row.id}` })
    },
    expand(record) {
      // this.productId = record.id
      this.productItemDetailList = []
      // this.expandedRowKeys = expanded ? [record.id] : []
      this.initLoading = true
      // if (expanded) {
      getListOnInfoItem({
        productId: record.id,
        locationId: this.search.locationId || null
      })
        .then((res) => {
          this.productItemDetailList = res
        })
        .finally(() => {
          this.initLoading = false
        })
      //  }
    },
    viewDetails(record) {
      this.viewDetailsModalRecord = record
      this.expand(record)
      getShareUrl({ productId: record.id }).then((res) => {
        this.creatQrCode(res.url)
        this.viewDetailsUrl = res.url
        this.viewPushUrl = res.pushUrl
      })
      companyWithUser({ userId: record.pmUserId }).then((res) => {
        if (res.length) {
          this.pmCompanyName = res[0].name
        }
      })
      this.viewDetailsModal = true
    },
    creatQrCode(text) {
      if (this.$refs.qrCodeUrl.childNodes.length) {
        let el = this.$refs.qrCodeUrl
        let childs = el.childNodes
        for (let i = childs.length - 1; i >= 0; i--) {
          el.removeChild(childs[i])
        }
      }

      let qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: text, // 需要转换为二维码的内容
        width: 145,
        height: 145,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      console.log(qrcode)
    },
    // 发布/隐藏
    uploadState({ item, key, keyPath }, record) {
      const _this = this
      let visible
      if (key === 1) {
        visible = record.visible === 1 ? 0 : 1
      } else if (key === 8) {
        visible = record.aroundVisible === 1 ? 0 : 1
      } else if (key === 9) {
        visible = record.regionVisible === 1 ? 0 : 1
      }
      this.$confirm({
        title: '温馨提示',
        content: '确定发布/隐藏？',
        centered: true,
        onOk() {
          const json = {
            id: record.id,
            locationId: record.locationId,
            visible: visible,
            type: key
          }

          releaseUpdate(json).then((res) => {
            if (res) {
              _this.query()
              _this.$messageSend.success('成功')
            }
          })
        },
        onCancel() {}
      })
    },
    // 推送
    pushOut(row) {
      if (this.search.locationId && this.search.locationId !== 10000) {
        const _this = this
        this.$confirm({
          title: '确定推送图文通知',
          content: '推送图文通知',
          centered: true,
          onOk() {
            const json = {
              id: row.id,
              locationId: _this.search.locationId
            }
            authorityAdmin(json).then((res) => {
              if (res) {
                _this.$messageSend.success('成功')
                _this.getNotice()
              }
            })
          },
          onCancel() {}
        })
      } else {
        this.$messageSend.error('请先选择非全国站的站点')
      }
    },
    // 隐藏显示的回调
    visibleChange(visible, record) {
      console.log(visible, record)
      if (visible && record.itemId) {
        productItemByOne({
          locationId: this.search.locationId || null,
          productItemId: record.itemId
        }).then((res) => {
          this.productItem = res
        })
      }
    },
    handleNationalCheck() {
      let dataJson = {
        id: this.viewDetailsModalRecord.id,
        // 可选值：1 本地商城 , 8 周边商城 , 9 UU地方 , 10 微课
        type: this.uploadKey,
        // 全国站上架站点集合
        locationIds: [],
        // 全国站下架站点集合
        subLocationIds: [],
        locationId: 10000,
        visible: 1
      }
      let shopName = this.uploadKey === 1 ? '本地商城' : this.uploadKey === 8 ? '周边商城' : this.uploadKey === 9 ? 'UU地方特产' : ''
      this.selectLocationIdList.forEach((el) => {
        dataJson.locationIds = dataJson.locationIds.concat(el.checkedList)
      })
      this.checkedList.forEach((el) => {
        if (!dataJson.locationIds.includes(el)) {
          dataJson.subLocationIds.push(el)
        }
      })
      // if (this.type === 10) {
      //   delete dataJson.locationIds
      //   delete dataJson.subLocationIds
      // }
      this.$confirm({
        title: `确认将以下产品上线到${shopName}选中的站点`,
        // content: (h) => <div style="color:red">{this.viewDetailsModalRecord.name}</div>,
        onOk: () => {
          releaseManagerUpdate(dataJson).then((res) => {
            this.$messageSend.success('操作成功!')
            this.nationalModal = false
          })
        }
      })
    },
    // 选择某个省下的所有站点
    onCheckAllChange(e, index) {
      this.selectLocationIdList[index].checkAll = e.target.checked
      this.selectLocationIdList[index].checkedList = e.target.checked ? this.selectLocationIdList[index].locations.map((el) => el.id) : []
      this.selectLocationIdList[index].indeterminate = false
      this.$forceUpdate()
    },
    // 选择单个站点
    checkChange(checkedList, index) {
      this.selectLocationIdList[index].indeterminate = !!checkedList.length && checkedList.length < this.selectLocationIdList[index].locations.length
      this.selectLocationIdList[index].checkAll = checkedList.length === this.selectLocationIdList[index].locations.length
      this.$forceUpdate()
    },
    showChooseLocation(row, type) {
      this.viewDetailsModalRecord = row
      this.uploadKey = type
      this.spinning = true
      getLocationAllProvince({ productId: row.id })
        .then((res) => {
          this.selectLocationIdList = res.records.map((el) => {
            el.checkedList = []
            el.locations.forEach((item) => {
              if (type === 1 && item.visible === 1) {
                el.checkedList.push(item.id)
                this.checkedList.push(item.id)
              }
              if (type === 8 && item.aroundVisible === 1) {
                el.checkedList.push(item.id)
                this.checkedList.push(item.id)
              }
              if (type === 9 && item.regionVisible === 1) {
                el.checkedList.push(item.id)
                this.checkedList.push(item.id)
              }
            })
            el.checkAll = el.locations.length === el.checkedList.length
            el.indeterminate = !!el.checkedList.length
            return el
          })
        })
        .finally(() => {
          this.spinning = false
        })
      this.nationalModal = true
    },
    appPush(record) {
      mscf.emit('redirect', '*', {
        target: 'market',
        page: 'addProductPush',
        params: {
          productId: record.id,
          onlyName: record.productName
        },
        query: {
          productId: record.id,
          onlyName: record.productName
        }
      })
    }
  },

  filters: {
    handleData: (val) => {
      if (!val && val !== 0) return '无'
      return val
    }
  }
}
</script>

<style scoped lang="less">
.simple[simple] {
  .qrcode {
    display: inline-block;
    img {
      width: 132px;
      height: 132px;
      background-color: #fff; //设置白色背景色
      padding: 6px; // 利用padding的特性，挤出白边

      box-sizing: border-box;
    }
  }
  .ml20 {
    margin-left: 20px;
  }
  .flexDiv {
    display: flex;
    justify-content: space-between;
  }
  .detailModal {
    display: flex;
    justify-content: space-between;
    .top {
      display: flex;
      width: 100%;
      justify-content: space-between;
      div {
        width: 350px;
      }
      div:nth-of-type(2) {
        margin-left: 120px;
      }
    }
  }
  .only-table {
    .only-table-locationName {
      position: relative;
      .stauts {
        position: absolute;
        left: -17px;
        top: -70px;
        padding: 1px;
        background: #ffaa1b;
        border-radius: 0px 10px 10px 0px;
        color: #fff;
      }
    }
  }
}
.remind-text {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #f5222d;
  line-height: 20px;
  margin-left: 12px;
}
/deep/ .ant-upload-list-picture-card .ant-upload-list-item,
/deep/ .ant-upload-list-picture-card-container {
  width: 50px;
  height: 50px;
  margin: 0;
  margin-right: 3px;
}
</style>
